package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * leetcode47 全排列II  medium
 */
public class LCode47 {
    private static List<List<Integer>> res = new ArrayList<>();
    private static List<Integer> list = new ArrayList<>();

    public static void main(String[] args) {
        int[] nums = {1,1,3};
        List<List<Integer>> permute = permuteUnique(nums);
        // 遍历集合中的集合
        Optional.ofNullable(permute).ifPresent(perm -> perm.forEach(per -> per.forEach(System.out::print)));
    }
    public static List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        boolean[] flag = new boolean[nums.length];
        dfs(nums, 0, flag);
        return res;
    }
    public static void dfs(int[] nums, int id, boolean[] flag) {
        if (id == nums.length) {
            res.add(new ArrayList<>(list));
            return ;
        }
        for (int i = 0; i < nums.length; i++) {
            // 去重逻辑，如果当前数与前一个相同，且前一个没有被使用，则跳过
            if (i > 0 && nums[i] == nums[i - 1] && flag[i - 1] == false) continue;
            if (flag[i]) continue;
            flag[i] = true;
            list.add(nums[i]);
            dfs(nums, id + 1, flag);
            flag[i] = false;
            list.remove(list.size() - 1);
        }
    }
}
